#include "mainwindow.h"
#include <QMessageBox>
#include "configurationdialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ConfigurationDialog dialog(this);
    if(dialog.exec() == QDialog::Rejected)
    {
        return;
    }
    ui->Player1Name->setText(dialog.Player1Name());
    ui->Player2Name->setText(dialog.Player2Name());

    connect(ui->gameBroad,&TicTacToeWidget::CurrentPlayerChanged,this,&MainWindow::UpdateNameLabels);
    connect(ui->gameBroad,&TicTacToeWidget::GameOver,this,&MainWindow::HanleGameOver);
    connect(ui->StartNewGame,&QAction::triggered,this,&MainWindow::StartGame);
    connect(ui->QuitGame,&QAction::triggered,qApp,&QApplication::quit);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::StartGame()
{
     ui->gameBroad->InitGame();
}

void MainWindow::SetLabelBlob(QLabel *p_label, bool isBlob)
{
    QFont t = p_label->font();
    t.setBold(isBlob);
    p_label->setFont(t);
}

void MainWindow::UpdateNameLabels()
{
    SetLabelBlob(ui->Player1Name,TicTacToeWidget::Player::Player1 == ui->gameBroad->GetCurrentPlayer());
    SetLabelBlob(ui->Player2Name,TicTacToeWidget::Player::Player2 == ui->gameBroad->GetCurrentPlayer());
}

void MainWindow::HanleGameOver(TicTacToeWidget::Player winner)
{
    QString messagne;
    if(winner == TicTacToeWidget::Player::Draw)
    {
        messagne = tr("Game End with Draw");
    }else
    {
        QString winnerName = winner == TicTacToeWidget::Player::Player1 ? ui->Player1Name->text() : ui->Player2Name->text();
        messagne = tr("%1 wins").arg(winnerName);
    }
    QMessageBox::information(this,tr("Info"),messagne);
}

